﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Aioms.Dtos;
using Aioms.Models;
using Furion;
using Furion.DataEncryption;
using Furion.DynamicApiController;
using Furion.UnifyResult;
using Magicodes.ExporterAndImporter.Core;
using Magicodes.ExporterAndImporter.Core.Extension;
using Magicodes.ExporterAndImporter.Excel;
using Mapster;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using OfficeOpenXml;
using SqlSugar;
using StackExchange.Profiling.Internal;

namespace Aioms.Controllers
{
    /// <summary>
    /// 报修
    /// </summary>
    [DynamicApiController]
    public class NoticeRepairResultController
    {
        private readonly IWebHostEnvironment _env;
        private readonly ISqlSugarClient db; // 核心对象：拥有完整的SqlSugar全部功能
        public NoticeRepairResultController(IWebHostEnvironment env, ISqlSugarClient sqlSugarClient)
        {
            this.db = sqlSugarClient;
        }

        /// <summary>
        /// 安卓端报修结果上传
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="npdto"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostSave([FromForm] NoticeRepairResultDto npdto)
        {
            // 如果当前结果已上传，提示已上传
            bool isAny = await db.Queryable<NrWorkOrder>()
                .Where(nrwo => nrwo.Eid == npdto.Eid)
                .Where(nrwo => nrwo.NpId == npdto.NpId)
                .Where(nrwo => nrwo.Status == "已完成").AnyAsync();
            if (isAny) {
                return new JsonResult(new RESTfulResult<object>
                {
                    StatusCode = -1,
                    Succeeded = false,
                    Data = null,
                    Errors = "该维修结果已经存在",
                    Extras = UnifyContext.Take(),
                    Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
                });
            }

            // 更新报修状态和工单状态
            await db.Updateable<NoticeRepair>(new NoticeRepair { Status = 6, ChuliStatus = "维修已完成" })
                .UpdateColumns(nr => new { nr.Status, nr.ChuliStatus })
                .Where(nr => nr.Id == npdto.NpId)
                .ExecuteCommandAsync();
            await db.Updateable<NrWorkOrder>(new NrWorkOrder { Status = "已完成", SjBeginTime = npdto.BeginTime, SjEndTime = npdto.EndTime, SjManHour = npdto.ManHour, SjProcedure = npdto.Procedure, SjResult = npdto.Result, SjWxEpId = npdto.RepairEpid, SjWxEpRealname = npdto.RepairEpRealname, SjImgUrl = npdto.ImgUrl == null ? new() : JArray.Parse(npdto.ImgUrl).ToObject<List<string>>(), SjVideoUrl = npdto.VideoUrl })
                .UpdateColumns(nrwo => new { nrwo.Status, nrwo.SjBeginTime, nrwo.SjEndTime, nrwo.SjManHour, nrwo.SjProcedure, nrwo.SjResult, nrwo.SjWxEpId, nrwo.SjWxEpRealname, nrwo.SjImgUrl, nrwo.SjVideoUrl })
                .Where(nrwo => nrwo.Eid == npdto.Eid && nrwo.NpId == npdto.NpId).ExecuteCommandAsync();
            
            // 如果正常运行，改变该设备状态，其他都不改变
            if (npdto.Result.Equals("正常")) {
                await db.Updateable<Device>().SetColumns(dv => dv.Status == "正常").Where(dv => dv.Eid == npdto.Eid && dv.Id == npdto.Dvid).ExecuteCommandAsync();
            }
            
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = null,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }
    }
}
